package com.fc.remoting.core;

public abstract class AbstractServerThread implements Runnable{
	
	protected final Thread thread;
	//thread回收时间
	private static final long JoinTime = 90 * 1000;
	//是否Notified
	protected volatile boolean hasNotified = false;
	//是否停止
	protected volatile boolean stoped = false;
	
	public AbstractServerThread(){
		thread = new Thread(this, this.getServiceName());
	}
	
	public abstract String getServiceName();
	
	public void start(){
		this.thread.start();
	}
	
	public void shutdown(){
		this.shutdown();
	}
	
	public void makeStop() {
        this.stoped = true;
    }
	
	public void stop(final boolean interrupt){
		this.stoped = true;
		synchronized (this) {
			if(!this.hasNotified){
				this.hasNotified = true;
				this.notify();
			}
		}
		
		if(interrupt){
			this.thread.interrupt();
		}
	}
	
	public void shutdown(final boolean interrupt){
		this.stoped = true;
		synchronized (this) {
			if(!this.hasNotified){
				this.hasNotified = true;
				this.notify();
			}
		}
		
		try{
			if(interrupt){
				this.thread.interrupt();
			}
			
			long begainTime = System.currentTimeMillis();
			this.thread.join(JoinTime);
			long spendTime = System.currentTimeMillis() - begainTime;
			System.out.println("join time:" + spendTime);
		}catch(InterruptedException e){
			e.printStackTrace();
		}
	}
	
	
	public void wakeup(){
		synchronized (this) {
			if(!this.hasNotified){
				this.hasNotified = true;
				this.notify();
			}
		}
	}
	
	protected void waitForRunning(long interval) {
        synchronized (this) {
            if (this.hasNotified) {
                this.hasNotified = false;
                this.onWaitEnd();
                return;
            }

            try {
                this.wait(interval);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            finally {
                this.hasNotified = false;
                this.onWaitEnd();
            }
        }
    }

    protected void onWaitEnd() {
    }

    public boolean isStoped() {
        return stoped;
    }

    public long getJointime() {
        return JoinTime;
    }
}
